<template>
  <div class="box-main">
    <el-card v-loading="loading" class="box-card">
      <TreeTools :item="header" :is-header="false" @show-dialog="showDialog" />

      <el-tree :data="list" :props="defaultProps">
        <template #default="{data}">
          <TreeTools :item="data" @show-dialog="showDialog" @del="delFn" />
        </template>
      </el-tree>
    </el-card>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      width="30%"
      @close="dialogClose"
      @open="dialogOpen"
    >
      <!-- 表单内容 -->
      <el-form ref="deptFrom" :rules="deptRules" :model="formData" label-width="120px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" placeholder="1-50个字符" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="formData.code" placeholder="1-50个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="formData.manager" placeholder="请选择负责人">
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :label="item.username"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input
            v-model="formData.introduce"
            type="textarea"
            :rows="2"
            placeholder="1-300个字符"
            :autosize="{ minRows: 4, maxRows: 10 }"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFn">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
// import transTree from '@/utils/transTree'
import toTree from '@/utils/toTree'
import { getDepartment, getManagerList, addDepartment, updateDeptmentInfo, getDeptmentInfo, delDeptment } from '@/api'
import TreeTools from './components/tree-tools.vue'
export default {
  components: {
    TreeTools
  },
  data() {
    // 同级部门中，不能出现相同的名称
    const validateName = (rule, value, callback) => {
      let broArr = []
      // 判断编辑状态下，修改部门名称时的校验
      if (this.formData.id) {
        // 判断当前输入的值，和节点中回显的值是否一致，如果一致，直接return
        if (value === this.currentNode.name) return callback()
        // 在原数据中，找到所有的兄弟，放入数组
        broArr = this.orginList.filter(item => item.pid === this.currentNode.pid)
      } else {
        // 在新增状态下找到父级下所有子集，放入数组
        broArr = this.orginList.filter(item => item.pid === this.currentNode.id)
      }
      // 判断当前输入与数组中元素名称是否相同
      broArr.some(item => item.name === value) ? callback(new Error('此部门名称已存在')) : callback()
    }
    // 所有部门中，不能存在相同的编码
    const validateCode = (rule, value, callback) => {
      // 排除编辑状态下，没有修改编码时，触发校验的问题
      if (this.formData.id && value === this.formData.code) return callback()
      this.orginList.some(item => item.code === value) ? callback(new Error('此编码已存在')) : callback()
    }
    return {
      // 表单验证规则
      deptRules: {
        name: [
          { required: true, message: '此项为必填项', tigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '请输入1-50个字符', tigger: ['blur', 'change'] },
          { validator: validateName, trigger: 'blur' }

        ],
        code: [
          { required: true, message: '此项为必填项', tigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '请输入1-50个字符', tigger: ['blur', 'change'] },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '此项为必填项', tigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '此项为必填项', tigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '请输入1-300个字符', tigger: ['blur', 'change'] }
        ]
      },
      // 页面加载动画
      loading: false,
      // 表单数据
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      dialogVisible: false,
      header: {
        name: '',
        manager: '',
        id: ''
      },
      list: [],
      orginList: [],
      // 修改树形插件的传参格式
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 当前点击的节点
      currentNode: {},
      // 负责人列表
      managerList: []
    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.fetchDepartment()
  },
  methods: {
    delFn(val) {
      this.$confirm('确定删除吗？此操作将永远删除该部门', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(async() => {
        await delDeptment(val.id)
        // 提示用户
        this.$message.success('删除成功')
        // 重新渲染页面
        this.fetchDepartment()
      })
    },
    async fetchDepartment() {
      this.loding = true
      try {
        const res = await getDepartment()
        // console.log(res)
        this.header.name = res.data.companyName
        // console.log(toTree(res.data.depts))
        this.orginList = res.data.depts
        this.list = toTree(res.data.depts)
        // this.list = transTree(res.data.depts)
      } catch (error) {
        console.log(error)
      }
      this.loding = false
    },
    // 获取部门详情
    async deptmentInfo(id) {
      const res = await getDeptmentInfo(id)
      this.formData = res.data
      console.log('0', this.formData)
    },
    showDialog(val, type) {
      if (type === 'edit') {
        this.deptmentInfo(val.id)
      }
      this.dialogVisible = true
      this.currentNode = val
      // console.log(val)
    },
    // 弹窗关闭时触发的函数
    dialogClose() {
      this.dialogVisible = false
      // 重置表单里面的输入框状态
      this.$refs['deptFrom'].resetFields()
      // 重置表单后，里面没有绑定的数据，并不能清空，可能会导致判断失效等问题
      // 为了防止数据污染，我们需要手动重置表单数据
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
    },
    // 打开弹出框时，调用获取员工列表接口，渲染页面
    async dialogOpen() {
      const { data } = await getManagerList()
      this.managerList = data
    },
    // 提交事件
    submitFn() {
      console.log('1', this.formData)
      // 兜底校验
      this.$refs.deptFrom.validate(async valid => {
        if (!valid) return
        // 根据数据中是否有id，来判断调用新增还是编辑
        if (this.formData.id) {
          // 调用编辑接口
          console.log('2', this.formData)
          await updateDeptmentInfo(this.formData)
        } else {
          // 调用新增接口
          console.log('111', this.formData)
          await addDepartment({
            ...this.formData,
            pid: this.currentNode.id
          })
        }
        // 提示用户添加成功
        this.$message.success(this.title + '成功')
        // 调用接口，重新渲染页面
        this.fetchDepartment()
        this.dialogVisible = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.box-main {
  padding: 20px;
  .box-card {
    padding: 30px;
  }
}
.el-select {
  width: 100%;
}
</style>
